package com.example.community.service;

import com.example.community.entity.DiscussPost;
import com.example.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class DataService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private DiscussPostService discussPostService;

    private SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");

    //将指定的ip放进uv
    public void recordUV(String ip){
        String redisKey = RedisKeyUtil.getUVKey(df.format(new Date()));
        redisTemplate.opsForHyperLogLog().add(redisKey,ip);
    }

    //计算当天的网站uv
    public long calculateUV(Date currentDate){
        if (currentDate == null){
            throw new IllegalArgumentException("参数不能为空");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        String key = RedisKeyUtil.getUVKey(df.format(calendar.getTime()));
        return redisTemplate.opsForHyperLogLog().size(key);
    }
    //统计当天的网站DAU
    public long calculateDAU(Date currentDate) {
        if (currentDate == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        String key = RedisKeyUtil.getDAUKey(df.format(calendar.getTime()));
        return (long)redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.bitCount(key.getBytes());
            }
        });

    }
    //统计指定日期范围内的uv
    public long calculateUV(Date start,Date end){
        if (start == null || end == null){
            throw new IllegalArgumentException("参数不能为空");
        }

        List<String> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        while (!calendar.getTime().after(end)){
            String key = RedisKeyUtil.getUVKey(df.format(calendar.getTime()));
            keyList.add(key);
            calendar.add(Calendar.DATE,1);
        }
        //合并数据
        String rediskey = RedisKeyUtil.getUVKey(df.format(start),df.format(end));
        redisTemplate.opsForHyperLogLog().union(rediskey,keyList.toArray());
        //返回统计结果
        return redisTemplate.opsForHyperLogLog().size(rediskey);
    }
    //将指定用户计算进去DAU
    public void recordDAU(int userId){
        //记录某一天是否活跃，bitMap,以userId作为索引
        String redisKey = RedisKeyUtil.getDAUKey(df.format(new Date()));
        redisTemplate.opsForValue().setBit(redisKey,userId,true);
    }
    // 统计指定日期范围内的DAU
    public long calculateDAU(Date start, Date end) {
        if (start == null || end == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }

        // 整理该日期范围内的key
        List<byte[]> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        while (!calendar.getTime().after(end)) {
            String key = RedisKeyUtil.getDAUKey(df.format(calendar.getTime()));
            keyList.add(key.getBytes());
            calendar.add(Calendar.DATE, 1);
        }

        // 进行OR运算
        //只要在指定的时间内进行了登录都是活跃用户
        return (long) redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                String redisKey = RedisKeyUtil.getDAUKey(df.format(start), df.format(end));
                connection.bitOp(RedisStringCommands.BitOperation.OR,
                        redisKey.getBytes(), keyList.toArray(new byte[0][0]));
                return connection.bitCount(redisKey.getBytes());
            }
        });
    }

}
